package com.boilerCloud.interceptors;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.boilerCloud.dto.sys.User;

/**
 * 业务使用的拦截器--主要针对资源权限判断
 * 
 * @author qianfuqiang
 */
public class HzlqswServiceInterceptor implements HandlerInterceptor {

	private static Logger log = LoggerFactory.getLogger(HzlqswServiceInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String path = request.getServletPath();
		String refererUrl = request.getHeader("referer");
		log.info("执行业务处理拦截开始" + path);
		// 获取当前session数据
		
		if (request.getSession().getAttribute("usersession") == null) {
			User user = new User();
			user.setId(1);
			user.setName("admin");
			user.setAccount("admin");
			user.setRoleId(1);
			request.getSession().setAttribute("usersession",user);
		}
		if (request.getSession().getAttribute("usersession") == null) {
			log.info("执行业务处理拦截不通过，没有权限" + path);
			if (refererUrl == null || refererUrl.endsWith("goLeft.do")) {
				//response.sendRedirect("../noLogin.do");
				response.sendRedirect("../nologin.jsp");
			} else {
				response.sendRedirect("noLogin.do");
			}
			return false;
		} else {
			User user = (User) request.getSession().getAttribute("usersession");
			
			log.info("用户{}执行操作{},所在ip地址={}", user.getAccount(), path, getUsrIPAddr(request));
			return true;
			
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		response.setHeader("Access-Control-Allow-Methods", "*");  
		response.setHeader("Access-Control-Max-Age", "3600");  
		response.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken");  
		response.setHeader("Access-Control-Allow-Credentials", "true");  
	}

	
    public String getUsrIPAddr(HttpServletRequest request) {  
        String ip = "";  
        ip = request.getHeader("x-forwarded-for");  
       //2.如果squid.conf的配制文件forwarded_for项默认是off，则：X-Forwarded-For：unknown。考虑用Proxy-Client-IP或WL-Proxy-Client-IP获取  
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        //3.最后考虑没有代理的情况，直接用request.getRemoteAddr()获取ip  
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  
        //4.如果通过多级反向代理，则可能产生多个ip，其中第一个非unknown的IP为客户端真实IP（IP按照','分割）  
        if(ip != null && ip.split(",").length > 1){  
            ip = (ip.split(","))[0];  
       }          
       //5.如果是服务器本地访问，需要根据网卡获取本机真实ip  
       if("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {  
            try {  
                ip = InetAddress.getLocalHost().getHostAddress();  
           } catch (UnknownHostException e) {  
               log.error(e.getMessage(),e);//获取服务器(本地)ip信息失败  
                return "";  
            }  
       }
       return ip; 
    }

}